/*
 * @Descripttion: 
 * @version: 
 * @Author: 某人
 * @Date: 2021-07-16 15:52:27
 */
let arr = [
  { id: 1, name: '部门1', pid: 0 },
  { id: 2, name: '部门2', pid: 1 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 },
]
function objFlat() {
  let hashMap = {}
  let result = []
  for (let item of arr) {
    if (!hashMap[item.pid]) {
      hashMap[item.pid] = []
    }
    if (hashMap[item.pid]) {
      hashMap[item.pid].push(item)
    }
  }
  for (let item of arr) {
    item.children = hashMap[item.id] || ''
  }
  // console.log('hashMap', JSON.stringify(hashMap))
  // console.log('arr', JSON.stringify(arr))
  result = hashMap['0']
  return JSON.stringify(result)
}
console.log('objFlat()', objFlat())